<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "user".
 *
 * @property int $id
 * @property string $username 用户名
 * @property string $password 密码
 * @property string $name 姓名
 * @property string $phone 手机号
 * @property string $openid_qq qq第三方id
 * @property string $openid_wx 微信第三方id
 * @property string $openid_wb 微博第三方id
 * @property string $header 头像
 * @property int $birth_day 生日
 * @property int $sex 性别
 * @property string $electric_code 电表号
 * @property int $company_id 认证企业id
 * @property int $repair_id 所属维修队id
 * @property int $is_admin 是否成为管理员
 * @property string $reg_id 设备唯一识别号
 * @property int $status 状态
 * @property int $created_at 创建时间
 */
class User extends Base
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['birth_day', 'sex', 'company_id', 'repair_id', 'is_admin', 'status', 'user_type', 'created_at'], 'integer'],
            [['username', 'password', 'name', 'phone', 'openid_qq', 'openid_wx', 'openid_wb', 'header', 'electric_code', 'reg_id', 'form_type_ids'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'name' => 'Name',
            'phone' => 'Phone',
            'openid_qq' => 'Openid Qq',
            'openid_wx' => 'Openid Wx',
            'openid_wb' => 'Openid Wb',
            'header' => 'Header',
            'birth_day' => 'Birth Day',
            'sex' => 'Sex',
            'electric_code' => 'Electric Code',
            'company_id' => 'Company ID',
            'repair_id' => 'Repair ID',
            'is_admin' => 'Is Admin',
            'reg_id' => 'Reg ID',
            'status' => 'Status',
            'created_at' => 'Created At',
        ];
    }

    public function getCompanyInfo(){
        return $this->hasOne(CompanyInfo::class, ['id' => 'company_id']);
    }

    public function getRepair(){
        return $this->hasOne(Repair::class, ['id' => 'repair_id']);
    }

    public function removeTokens(){
        UserLogin::deleteAll(
            'user_id = :user_id and token != :token',
            [':user_id'=>$this->id, ':token'=>$this->getBearToken()]
        );
    }

    private function getBearToken(){
        $authHeader = Yii::$app->getRequest()->getHeaders()->get('Authorization');
        if (preg_match('/^Bearer\s+(.*?)$/', $authHeader, $matches)) {
            return $matches[1];
        } else {
            return null;
        }
    }
}
